package DOM;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DXpath {
	public static void main(String[] args) {
		try {
			readX();
		} catch (XPathExpressionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void readX() throws ParserConfigurationException,
			SAXException, IOException, XPathExpressionException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// 2.产生解析器
		DocumentBuilder builder = factory.newDocumentBuilder();
		// 3.解析xml文档，得到代表文档的document
		Document document = builder.parse(new File("src/resource/node.xml"));
		XPathFactory fpath = XPathFactory.newInstance();
		XPath xpath = fpath.newXPath();
		XPathExpression expr = xpath
				.compile("bookstore/book[1]//@lang/ancestor::book");
		Object result = expr.evaluate(document, XPathConstants.NODESET);
		NodeList resultList = (NodeList) result;
		for (int i = 0; i < resultList.getLength(); i++) {
			Node node = resultList.item(i);
			String nodeName = node.getNodeName();
			String text = node.getTextContent();
			System.out.println(nodeName + " --> " + text);
		}
	}
}
